package com.dahua.messagesyncsh.business.mitsubishi.controller;

import com.alibaba.fastjson2.JSONObject;
import com.dahua.messagesyncsh.business.mitsubishi.common.constant.EventTypeEnum;
import com.dahua.messagesyncsh.business.mitsubishi.http.ApiServiceResponse;
import com.dahua.messagesyncsh.business.mitsubishi.util.HttpResultUtil;
import com.dahua.messagesyncsh.business.mitsubishi.util.OkHttpUtils;
import com.dahua.messagesyncsh.config.redis.RedisUtil;
import com.dahua.messagesyncsh.criteria.EquipmentQueryCriteria;
import com.dahua.messagesyncsh.entity.Equipment;
import com.dahua.messagesyncsh.service.EquipmentService;
import com.smec.zhdt.openapi.call.client.common.util.CallClientEncryptUtils;
import com.smec.zhdt.openapi.call.client.vo.EncryptedVo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

import static com.dahua.messagesyncsh.common.Constants.MITSUBISHI_SYNC_EQUIPMENT;
import static com.smec.zhdt.openapi.call.client.common.constant.ApiServiceCommonCodeUtils.SUCCESS_CODE;

@Slf4j
@Component("mitsubishiSchedule")
@EnableAsync
public class Schedule {

    @Value("${mitsubishi.feign.url}")
    private String url;

    @Value("${mitsubishi.is-subscribe}")
    private String isSubscribe;

    @Value("${mitsubishi.sync.lineIds}")
    private String lineIds;

    @Value("${mitsubishi.sync.brandId}")
    private String brandId;



    @Value("${mitsubishi.callAppKey:rK5HUbFgsRjuD03x39za0zD3jY5KT0Nm}")
    private String callAppKey;

    @Value("${mitsubishi.callAppSecretKey:boDXcROSQ7Yf2R0mx6l7rikOWAEOFgSAsca2KbT9Xvy}")
    private String callAppSecretKey;

    @Value("${mitsubishi.callAppId:ZHDT20250526_6fc4e9ead4b942889382e3dab7b775d3}")
    private String corpId;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private EquipmentService  equipmentService;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void subscribe() {

        if (!isSubscribe.equals("true")) {
            return;
        }

        List<String> bk1s = new ArrayList<String>();

        Object string = redisUtil.getString(MITSUBISHI_SYNC_EQUIPMENT);
        if (string == null || string.toString().isEmpty()) {
            List<Equipment> equipments =
                    equipmentService.detail(EquipmentQueryCriteria.builder().lindIdsIn(Arrays.asList(11, 2, 8, 12)).brandId(104).build());

            for (Equipment equipment : equipments) {
                if (equipment.getBk1() != null && !equipment.getBk1().isEmpty()) {
                    bk1s.add(equipment.getBk1());
                }
            }

            if (!bk1s.isEmpty()) {
                redisUtil.setString(MITSUBISHI_SYNC_EQUIPMENT, bk1s);
            }
        }else{
            try{
                bk1s = (List<String>) JSONObject.parseObject(JSONObject.toJSONString(string), List.class);
            }catch (Exception e){
                log.error("【MitsubishiSchedule】：缓存数据转换失败 {}", string);
            }
        }

        if (bk1s.isEmpty()) {
            return;
        }


        Map<String, Object> subscribe = new HashMap<>();

        try{
            ModifySubscriptionEventRequestDto modifySubscriptionEventRequestDto = new ModifySubscriptionEventRequestDto();
            modifySubscriptionEventRequestDto.setStatus("on");
            ModifySubscriptionEventSpecDto spec = new ModifySubscriptionEventSpecDto();

            spec.setEleContractNo(bk1s);

            modifySubscriptionEventRequestDto.setSpec(spec);

            CallClientEncryptUtils<ModifySubscriptionEventRequestDto> decryptUtils = new
                    CallClientEncryptUtils<>(callAppKey, callAppSecretKey, corpId);

            EncryptedVo<ModifySubscriptionEventRequestDto> encryptedData = decryptUtils.getEncryptedData(modifySubscriptionEventRequestDto);

            log.info("【MitsubishiSchedule】：发送数据为{}",encryptedData);

            String encryptedDataStr = decryptUtils.getEncryptedDataStr(modifySubscriptionEventRequestDto);

            String returnResultsStr = OkHttpUtils.builder()
                    .url(url + corpId + "/v1/openapi/call/common/modify/subscription/event/" + String.valueOf(EventTypeEnum.REALTIME_DATA))
                    .setSendParam(encryptedDataStr)
                    .sendSyncRequest();

            HttpResultUtil<Map<String, Object>> result = new HttpResultUtil<>();
            ApiServiceResponse<Map<String, Object>> mapApiServiceResponse = result.getResponseObj(returnResultsStr);

            if (!SUCCESS_CODE.equals(mapApiServiceResponse.getCode())) {
                log.error("【MitsubishiSchedule】：订阅失败 {}", mapApiServiceResponse.getData());
            } else {
                log.info("【MitsubishiSchedule】：订阅成功");
            }

        }catch (Exception e){
            log.error("【MitsubishiSchedule】：其他失败 {}", e.getMessage());
        }

    }


    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ModifySubscriptionEventRequestDto {
        private String status;
        private ModifySubscriptionEventSpecDto spec;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ModifySubscriptionEventSpecDto {
        private String frequency;
        private Integer rtDuration;
        private List<Long> eleId;
        private List<String> customerEleId;
        private List<String> eleContractNo;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Return {

        private String code;

        private String message;

        private Integer total;

        private Object data;

        private String requestId;

        private String requestid;
    }
}
